package com.imooc.distributelockstock.lock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class RedisLock extends AbstractLock{




    public StringRedisTemplate stringRedisTemplate;

    private final long defaultExpireTime = 300000;
    private final String uuid;
    public RedisLock(StringRedisTemplate stringRedisTemplate, String lockName){
        this.lockName = lockName;
        this.stringRedisTemplate = stringRedisTemplate;
        this.uuid = UUID.randomUUID().toString();
    }

    @Override
    public void lock(){
        lock(TimeUnit.MILLISECONDS,defaultExpireTime);
    }

    @Override
    public void lock(TimeUnit timeUnit, long expireTime) {
        // 1.使用setnx指令进行加锁
        while (true){
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(this.lockName, uuid,expireTime,timeUnit);
            if(result!=null && result){
                //获取锁成功，跳出循环
                break;
            }

            try{
                Thread.sleep(50);
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        }

    }

    @Override
    public void unlock() {
        //判断当前持有锁线程是否等于本线程，是则直接删除，不是直接return
        String result = stringRedisTemplate.opsForValue().get(this.lockName);
        if(this.uuid.equals(result)){
            stringRedisTemplate.delete(this.lockName);
        }

    }
}
